<?php

namespace addons\facrm\controller;

use think\Config;
use think\Db;
use think\Queue;

/**
 * 定时任务
 * @internal
 */
class Autotask extends \think\addons\Controller
{
    protected $noNeedLogin = ["*"];
    protected $layout = '';

    public function _initialize()
    {
        set_time_limit(0);
        parent::_initialize();

        if (!$this->request->isCli()) {
            $this->error('只允许在终端进行操作!');
        }
    }

    /**
     * 定时任务逻辑
     */
    public function index()
    {
        $this->flowcustomer();
        $this->flowbusiness();
        $this->expirecontract();
        $this->expirecustomer();
        $this->flowclues();
    }

    /**
     * 待跟进客户提醒
     */
    public function flowcustomer()
    {

        //当天开始时间
        $start_time = strtotime(date("Y-m-d", time()));
        //当天结束之间
        $end_time = $start_time + 60 * 60 * 24;
        $customerModel = model('\app\admin\model\facrm\Customer');
        //需要联系客户
        $communicate = $customerModel->where('next_time', 'between', [1, $end_time])
            ->field('COUNT(*) AS count,owner_user_id ')
            ->where('owner_user_id', "<>", '0')
            ->group('owner_user_id')
            ->select();

        foreach ($communicate as $row) {
            if ($row->count <= 0) continue;
            //通知队列
            Queue::push("addons\\facrm\\library\\notice\queue\\CustomerJob", [
                'key' => 'notice_flow_customer',//待跟进通知模板
                'admin_ids' => $row->owner_user_id,
                'count' => $row->count,
            ]);
        }
        echo "done";
        return;
    }

    /**
     * 待跟进线索提醒
     */
    public function flowclues()
    {

        //当天开始时间
        $start_time = strtotime(date("Y-m-d", time()));
        //当天结束之间
        $end_time = $start_time + 60 * 60 * 24;
        $cluesModel = model('\app\admin\model\facrm\Clues');
        //需要联系线索
        $communicate = $cluesModel->where('next_time', 'between', [1, $end_time])
            ->field('COUNT(*) AS count,owner_user_id ')
            ->where('owner_user_id', "<>", '0')
            ->group('owner_user_id')
            ->select();

        foreach ($communicate as $row) {
            if ($row->count <= 0) continue;
            //通知队列
            Queue::push("addons\\facrm\\library\\notice\queue\\CluesJob", [
                'key' => 'notice_flow_clues',//待跟进通知模板
                'admin_ids' => $row->owner_user_id,
                'count' => $row->count,
            ]);
        }
        echo "done";
        return;
    }

    /**
     * 待跟进商机提醒
     */
    public function flowbusiness()
    {
        //当天开始时间
        $start_time = strtotime(date("Y-m-d", time()));
        //当天结束之间
        $end_time = $start_time + 60 * 60 * 24;
        $thisModel = model('\app\admin\model\facrm\Business');
        //需要联系
        $communicate = $thisModel->where('next_time', 'between', [1, $end_time])
            ->where('is_end', 0)
            ->field('COUNT(*) AS count,owner_user_id ')
            ->where('owner_user_id', "<>", '0')
            ->group('owner_user_id')
            ->select();

        foreach ($communicate as $row) {
            if ($row->count <= 0) continue;
            //通知队列
            Queue::push("addons\\facrm\\library\\notice\queue\\BusinessrJob", [
                'key' => 'notice_flow_business',//待跟进通知模板
                'admin_ids' => $row->owner_user_id,
                'count' => $row->count,
            ]);
        }
        echo "done";
        return;
    }

    /**
     * 将过期合同（提前三十天）
     */
    public function expirecontract()
    {

        //当天开始时间
        $start_time = strtotime(date("Y-m-d", time()));
        //当天结束之间
        $end_time = $start_time + 60 * 60 * 24;
        $thisModel = model('\app\admin\model\facrm\Contract');
        //需要联系
        $communicate = $thisModel->where('end_time', 'between', [1, $end_time + (30 * 86400)])
            ->where('expire_handle', 0)
            ->field('COUNT(*) AS count,owner_user_id ')
            ->where('owner_user_id', "<>", '0')
            ->group('owner_user_id')
            ->select();

        foreach ($communicate as $row) {
            if ($row->count <= 0) continue;
            //通知队列
            Queue::push("addons\\facrm\\library\\notice\queue\\ContractJob", [
                'key' => 'notice_expire_contract',//待跟进通知模板
                'admin_ids' => $row->owner_user_id,
                'count' => $row->count,
            ]);
        }
        echo "done";
        return;

    }


    /**
     * 将要过期客户提醒
     */
    public function expirecustomer()
    {

        $config = get_addon_config('facrm');
        //判断是否开启过期的功能
        if ($config['lose_day1'] <= 0 && ($config['lose_day2'] <= 0)) {
            echo "done none";
            return;
        }

        $thisModel = model('\app\admin\model\facrm\Customer');

        $lists = $thisModel->getLoseWhere($config, 1)
            ->field('COUNT(*) AS count,owner_user_id ')
            ->where('owner_user_id', "<>", '0')
            ->group('owner_user_id')
            ->select();

        foreach ($lists as $row) {
            if ($row->count <= 0) continue;
            //通知队列
            Queue::push("addons\\facrm\\library\\notice\queue\\CustomerJob", [
                'key' => 'notice_expire_ccustomer',//客户将过期通知模板
                'admin_ids' => $row->owner_user_id,
                'count' => $row->count,
            ]);
        }
        echo "done";
        return;
    }


    /**
     * 云呼记录同步云呼建议1个小时执行一次
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function  calllog(){
        $this->key = "cloudcall";
        //获取云呼配置
        $all_types = \addons\facrm\library\cloudcall\Call::getProviders();
        $keys = "";
        foreach ($all_types as $v) {
            $keys .= $keys ? ',' . $this->key . $v : $this->key . $v;
        }
        $settingModel = new \app\admin\model\facrm\Setting();
        $setting = $settingModel->where('key', 'in', $keys)->where('status', 1)->find();//只找一条云呼通道

        if (!$setting) {
            $this->error(__("云呼通道没有配置，请先配置"));
        }
        //获取坐席

        $setting = $setting->toArray();
        $setting['key'] = $setting['describe'];
        $setting = array_merge($setting, $setting['values']);
        $call = \addons\facrm\library\cloudcall\Call::instance($setting);



        $calldata['beginTime'] =datetime( time()-(86400*1), 'Y-m-d H:i:s') ;//开始时间
        $calldata['endTime'] =datetime( time(), 'Y-m-d H:i:s');//结束时间


        $result = $call->getCallRecord($calldata);
        if (!$result) {
            $this->error($call->getError());
        }
        $result=json_decode($result,true);
        if (isset($result['success'])&&$result['success']&&$result['data']){
            $cloudcallLog=new \app\admin\model\facrm\CloudcallLog();
            foreach ($result['data'] as $r){
                if (!$r['ACTION_ID']) continue;

                $log=$cloudcallLog->where('action_id',$r['ACTION_ID'])->where('status',0)->find();
                if (!$log) continue;

                $log->call_no=$r['CALL_NO'];
                $log->status=$r['STATUS']=='dealing'?1:-1;
                $log->record_file=$r['FILE_SERVER'].'/'.$r['RECORD_FILE_NAME'];
                $log->call_time_length=$r['CALL_TIME_LENGTH'];

                $log->save();
            }

        }
    }

}